package com.tanhua.dubbo.server.api;

import com.alibaba.dubbo.config.annotation.Service;
import com.tanhua.dubbo.server.pojo.Video;
import com.tanhua.dubbo.server.vo.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @author why
 */
@Service(version = "1.0.0")
public class ManageVideoApiImpl implements ManageVideoApi {

    /**
     * 根据排序字段 查询用户的视频记录 进行分页
     * @param uid
     * @param page
     * @param pageSize
     * @param sortProp
     * @param sortOrder
     * @return
     */

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public PageInfo<Video> queryVideoByUid(Integer uid, Integer page, Integer pageSize , String sortProp, String sortOrder) {
        PageInfo<Video> pageInfo=new PageInfo<>();
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(pageSize);

        if (StringUtils.equals("creatDate",sortProp)){
            sortProp="created";
        }
        PageRequest pageRequest=null;
        if ("ascending".equals(sortOrder)){

           pageRequest =PageRequest.of(page-1,pageSize,Sort.by(Sort.Order.asc(sortProp)));
        }else {
           pageRequest =PageRequest.of(page-1,pageSize,Sort.by(Sort.Order.desc(sortProp)));
        }

        Query query=Query.query(Criteria.where("userId").is(uid)).with(pageRequest);
        List<Video> videos = this.mongoTemplate.find(query, Video.class);
        if (CollectionUtils.isEmpty(videos)){
            return pageInfo;
        }
        Query queryCount=Query.query(Criteria.where("userId").is(uid));
        long count = this.mongoTemplate.count(queryCount, Video.class);

        pageInfo.setTotal((int) count);
        pageInfo.setRecords(videos);

        return pageInfo;
    }
}
